package org.example.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hxy
 * @date 2021/1/12
 */
public class JwtTokenUtil {
    public static String SECRET = "abcdefg";

    public static String USER_KEY="userid";

    public static String createToken(String userId) throws Exception{
        //签发时间
        Date istDate = new Date();

        //设置过期时间
        Calendar nowTime = Calendar.getInstance();
        //增加一天的过期时间
        nowTime.add(Calendar.DATE,1);
        Date expiresDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)
                .withClaim(USER_KEY, userId)
                .withExpiresAt(expiresDate)
                .withIssuedAt(istDate)             //
                .sign(Algorithm.HMAC256(SECRET));   //对头部和载荷进行签名
        return token;


    }


    public static String verifyToken(String token) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();  //使用SECRET和HS256对头部和载荷进行签名，和第三部分的签名进行对比
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new RuntimeException("凭证过期！");
        }
        return jwt.getClaim(USER_KEY).asString();
    }
}
